package com.kstudio.videocapture.listfile.fileaction;

import java.io.File;
import java.util.ArrayList;
import java.util.Map;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.kstudio.videocapture.R;
import com.kstudio.videocapture.listfile.KFileListExternalStorage;
import com.kstudio.videocapture.listfile.KFileListItem;
import com.kstudio.videocapture.util.KLog;

public class KFileActionActivity extends Activity {
    private final KLog log = new KLog("KFileList");

    public static final String      MODE        = "FileActionMode";
    public static final String      PATH        = "FileActionPath";

    private int mMode;
    private String mPath;
    private String mFilePath;

    private Context       mContext;

    private ListView                    mListView;
    private ArrayList<KFileActionItem>  mFileList;
    private KFileActionAdapter          mAdapter;

    private TextView                    mTextView;

    private ProgressBar                 mProgressBar;

    private String                      mSdCard;
    private String                      mExtsdCard;
    private String                      mRoot;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        log.i("***************** onCreate *****************");
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
        if(intent != null) {
            mMode = intent.getIntExtra(KFileActionUtil.MODE, KFileActionUtil.MODE_COPY);
            mFilePath = intent.getStringExtra(KFileActionUtil.PATH);
            if(mFilePath == null) {
                finishActivity();
            }
            int separatorIndex = mFilePath.lastIndexOf(File.separator);
            if(separatorIndex > 0)
                mPath = mFilePath.substring(0, separatorIndex);
            else
                finishActivity();
        } else {
            finishActivity();
        }

        Map<String, File> externalLocations = KFileListExternalStorage.getAllStorageLocations();
        mSdCard = externalLocations.get(KFileListExternalStorage.SD_CARD).getPath();
        mExtsdCard = null;
        if(externalLocations.size() > 1) {
            mExtsdCard = externalLocations.get(KFileListExternalStorage.EXTERNAL_SD_CARD).getPath();
        }
        mRoot = mSdCard.substring(0, mSdCard.lastIndexOf(File.separator));

        setContentView(R.layout.file_action_activity);

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);

        init();
    }

    @Override
    protected void onResume() {
        log.i("***************** onResume *****************");

        super.onResume();
    }

    @Override
    protected void onPause() {
        log.i("***************** onPause *****************");

        super.onPause();
    }

    @Override
    protected void onStop() {
        log.i("***************** onStop *****************");

        super.onStop();
    }

    @Override
    protected void onDestroy() {
        log.i("***************** onDestroy *****************");

        super.onDestroy();
    }

    /* Menu */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_fileaction, menu);
        return true;
    }

    /* Event */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case android.R.id.home:
                finishActivity();
            return true;

            case R.id.menu_fileaction_addfolder:

            return true;

            case R.id.menu_fileaction_done:
                actionDone();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
    }

    private class KOnItemClickListenr implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int i, long l) {
            KFileActionItem fileData = (KFileActionItem) adapterview.getItemAtPosition(i);

            if(fileData.getFileType() == KFileActionItem.FOLDERUP) {
                if(mPath.equals(mSdCard) || mPath.equals(mExtsdCard)) {
                    mPath = makeFileList(mRoot);
                } else {
                    int separatorIndex = mPath.lastIndexOf(File.separator);

                    if(separatorIndex > 0)
                        mPath = makeFileList(mPath.substring(0, separatorIndex));
                }
            } else if(fileData.getFileType() == KFileActionItem.FOLDER) {
                mPath = makeFileList(fileData.getPath());
            }
        }
    }

    /* private */
    private void init() {
        mContext = this;
        mFileList = new ArrayList<KFileActionItem>();
        mAdapter = new KFileActionAdapter(this, mFileList);

        mTextView = (TextView)findViewById(R.id.fileaction_path);

        mListView = (ListView)findViewById(R.id.fileaction_list);

        mPath = makeFileList(mPath);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new KOnItemClickListenr());

        mProgressBar = (ProgressBar)findViewById(R.id.fileaction_progressBarStyleLarge);

    }

    private String makeFileList(String path) {
        String result = updateFileList(path);
        mTextView.setText(result);
        mAdapter.notifyDataSetChanged();
        return result;
    }

    private String updateFileList(String path) {
        /* Storage directory */
        String currentpath = path;
        File[] files = new File(currentpath).listFiles();
        String root = "..";

        mFileList.clear();
        if(files == null) {
            mFileList.add(new KFileActionItem(root, KFileListItem.FOLDERUP));
            return currentpath;
        } else if(path.equals(mRoot)) {
            mFileList.add(new KFileActionItem(mSdCard, KFileListItem.FOLDER));
            if(mExtsdCard != null) {
                mFileList.add(new KFileActionItem(mExtsdCard, KFileListItem.FOLDER));
            }
            return mRoot;
        }

        mFileList.add(new KFileActionItem(root, KFileListItem.FOLDERUP));

        for(File file: files) {
            if(file.isDirectory() && !file.getName().startsWith(".")) {
                mFileList.add(new KFileActionItem(file.getPath(), KFileListItem.FOLDER));
            }
        }

        return currentpath;
    }

    private boolean actionDone() {
        File file = new File(mFilePath);
        if(!file.exists()) {
            return false;
        }

        switch(mMode) {
            case KFileActionUtil.MODE_COPY:
            case KFileActionUtil.MODE_MOVE:
            {
                mProgressBar.setVisibility(View.VISIBLE);
                new KFileActionUtil(mMode, mFilePath, mPath+File.separator+file.getName(), new KFileActionUtil.KFileActionUtilListener() {
                    @Override
                    public void onProgress(int time) {

                    }

                    @Override
                    public void onError() {
                        mProgressBar.setVisibility(View.GONE);
                        finishActivity();
                    }

                    @Override
                    public void onComplete() {
                        mProgressBar.setVisibility(View.GONE);
                        finishActivity();                    }
                });
            }
            break;
        }

        return true;
    }

    private void finishActivity() {
        finish();
    }
}
